/**
 * Created by macos on 14/10/27.
 */

var uuid = require('node-uuid');

var messageQ = require('./message-q');

(function() {
  var TCPServer = {};
  var root = this;

  var redisClient = Redis.client();

  TCPServer.bootstrap = function(config) {
    sails.log.info('------------------- TCP Server -------------------------');

    //初始化配置文件
    config.port = config.port || 1733;
    config.clientTimeout = config.clientTimeout || 60000;
    config.clientExpire = config.clientExpire || -1;

    //创建TCP服务器
    var server = require("./tcp-engine").createServer(config);
    server.listen(config.port);
    sails.log.info('port:', config.port);

    server.on('clientConnection', function(res) {
      res.id = 'clients:id:' + uuid.v1();

      //设置客户端连接的session会话
      redisClient.hmset(res.id, {
        remoteAddress: res.remoteAddress,
        remotePort: res.remotePort,
        expire: config.clientExpire
      });
      redisClient.expire(res.id, config.clientExpire);

      redisClient.hgetall(res.id, function(err, value) {
        sails.log.debug(res.id + ": ", value.remoteAddress, value.remotePort);
      });

      res.on('close', function() {
        sails.log.debug('close: ', res.id);
        redisClient.del(res.id);
//        messageQ.removeChannel(channel)
      });

      res.on('error', function(e) {
        sails.log.error(res.id, e);
      });

      res.on('timeout', function() {
        sails.log.debug('timeout: ', res.id);
        res.destroy();
      });

    });

    //运行协议
    var login = require('./protocol/login-protocol')
    login.runProtocol(server);

    var heart = require('./protocol/heart-protocol')
    heart.runProtocol(server);

    var data = require('./protocol/data-protocol')
    data.runProtocol(server);

    sails.log.info('--------------------------------------------------------\n');
  }

  module.exports = TCPServer;
})();